<script>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { User, Lock } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'

export default {
  name: "login",
  components: {
    User,
    Lock
  },
  setup() {
    const formRef = ref(null)
    const router = useRouter()

    return {
      formRef,
      router
    }
  },
  data() {
    return {
      formModel: {
        username: '',
        password: '',
        repassword: ''
      },
      isRegister: false,
      isReSetPassword: false,
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 5, max: 10, message: '用户名必须5-10位字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { pattern: /^\S{6,15}$/, message: '密码必须是6-15位非空字符', trigger: 'blur' }
        ],
        repassword: [
          { required: true, message: '请再次输入密码', trigger: 'blur' },
          { pattern: /^\S{6,15}$/, message: '密码必须是6-15位非空字符', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value !== this.formModel.password) {
                callback(new Error('两次输入密码不一致'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ]
      }
    }
  },

  methods: {
    // 重置密码
    async reSetPassword() {
      try {
        await this.$refs.formRef.validate()
        const res = await this.$axios.post('/resetpassword', this.formModel)
        if (res.data.code === 200) {
          ElMessage.success('密码重置成功')
          this.resetForm()
          this.isReSetPassword = false
        } else {
          ElMessage.error(res.data.msg || '密码重置失败')
        }
      } catch (error) {
        console.error('密码重置失败:', error)
        ElMessage.error('密码重置失败，请稍后重试')
      }
    },

    // 注册
    async register() {
      try {
        await this.$refs.formRef.validate()
        const res = await this.$axios.post('/register', this.formModel)
        if (res.data.code === 200) {
          ElMessage.success('注册成功')
          this.resetForm()
          this.isRegister = false
        } else {
          ElMessage.error(res.data.msg || '注册失败')
        }
      } catch (error) {
        console.error('注册失败:', error)
        ElMessage.error('注册失败，请稍后重试')
      }
    },

    // 登录
    async submitForm() {
      try {
        await this.$refs.formRef.validate()
        const res = await this.$axios.post('/login', this.formModel)

        const jwt = res.headers['authorization']
        const userInfo = res.data.data

        if (!userInfo) {
          ElMessage.error('登录响应数据为空')
          return
        }

        if (!userInfo.role) {
          ElMessage.error('用户角色信息缺失')
          return
        }

        const requiredFields = ['id', 'username', 'realName', 'role']
        const missingFields = requiredFields.filter(field => !userInfo[field])

        if (missingFields.length > 0) {
          ElMessage.error(`登录响应缺少必要信息: ${missingFields.join(', ')}`)
          return
        }

        const normalizedUserInfo = {
          id: userInfo.id,
          username: userInfo.username,
          realName: userInfo.realName || '默认姓名', // 提供默认值
          role: userInfo.role.toLowerCase(),
          avatar: userInfo.avatar || '',
          email: userInfo.email || '',
          status: userInfo.status|| '',
          phone: userInfo.phone|| '',
          birthday:userInfo.birthday|| '',
          sex:userInfo.sex|| '',
        }

        // 存储令牌和用户信息
        localStorage.setItem('token', jwt)
        localStorage.setItem('userRole', normalizedUserInfo.role)
        sessionStorage.setItem('userInfo', JSON.stringify(normalizedUserInfo))

        // Vuex存储
        this.$store.commit("SET_TOKEN", jwt)
        this.$store.commit("SET_USERINFO", normalizedUserInfo)

        ElMessage.success(`欢迎回来，${normalizedUserInfo.username}`)

        const redirectPath = `/${normalizedUserInfo.role}`

        try {
          await this.$router.push(redirectPath)
        } catch (navigationError) {
          console.error('导航错误:', navigationError)
          ElMessage.error('页面跳转失败，请刷新重试')
        }

      } catch (error) {
        console.error('登录失败:', error)

        if (error.response) {
          const status = error.response.status
          switch (status) {
            case 400:
              ElMessage.error('用户名或密码错误')
              break
            case 401:
              ElMessage.error('未授权，请重新登录')
              break
            case 403:
              ElMessage.error('访问被拒绝')
              break
            case 500:
              ElMessage.error('服务器错误，请稍后重试')
              break
            default:
              ElMessage.error('登录失败，请稍后重试')
          }
        } else if (error.request) {
          ElMessage.error('网络错误，请检查网络连接')
        } else {
          ElMessage.error('登录失败，请检查用户名和密码')
        }

        this.formModel.password = ''
      }
    },

    // 重置表单
    resetForm() {
      this.$refs.formRef.resetFields()
    }
  }
}
</script>

<template>
  <div class="login-container">
    <div class="login-box">
      <!-- 左侧信息区 -->
      <div class="info-section">
        <img src="@/assets/logo.png" alt="Logo" class="logo">
        <h1>学习营活动管理平台</h1>
        <p>让学营启航，让梦想飞扬</p>
      </div>

      <!-- 右侧登录区 -->
      <div class="login-section">
        <div class="login-content">
          <h2>{{ isRegister ? '注册账号' : (isReSetPassword ? '重置密码' : '欢迎登录') }}</h2>

          <!-- 登录表单 -->
          <el-form
              v-if="!isRegister && !isReSetPassword"
              ref="formRef"
              :model="formModel"
              :rules="rules"
              class="login-form"
          >
            <div class="input-group">
              <el-input
                  v-model="formModel.username"
                  placeholder="用户名"
                  :prefix-icon="User"
              />
            </div>
            <div class="input-group">
              <el-input
                  v-model="formModel.password"
                  type="password"
                  placeholder="密码"
                  :prefix-icon="Lock"
              />
            </div>
            <div class="options">
              <el-checkbox>记住我</el-checkbox>
              <el-link type="primary" @click="isReSetPassword = true">忘记密码？</el-link>
            </div>
            <el-button type="primary" class="submit-btn" @click="submitForm">
              登录
            </el-button>
            <div class="register-link">
              还没有账号？<el-link type="primary" @click="isRegister = true">立即注册</el-link>
            </div>
          </el-form>

          <!-- 注册表单 -->
          <el-form
              v-if="isRegister"
              ref="formRef"
              :model="formModel"
              :rules="rules"
              class="register-form"
          >
            <div class="input-group">
              <el-input
                  v-model="formModel.username"
                  placeholder="请输入用户名"
                  :prefix-icon="User"
              />
            </div>
            <div class="input-group">
              <el-input
                  v-model="formModel.password"
                  type="password"
                  placeholder="请输入密码"
                  :prefix-icon="Lock"
              />
            </div>
            <div class="input-group">
              <el-input
                  v-model="formModel.repassword"
                  type="password"
                  placeholder="请确认密码"
                  :prefix-icon="Lock"
              />
            </div>
            <el-button type="primary" class="submit-btn" @click="register">
              注册
            </el-button>
            <div class="login-link">
              已有账号？<el-link type="primary" @click="isRegister = false">返回登录</el-link>
            </div>
          </el-form>

          <!-- 重置密码表单 -->
          <el-form
              v-if="isReSetPassword"
              ref="formRef"
              :model="formModel"
              :rules="rules"
              class="reset-form"
          >
            <div class="input-group">
              <el-input
                  v-model="formModel.username"
                  placeholder="请输入用户名"
                  :prefix-icon="User"
              />
            </div>
            <div class="input-group">
              <el-input
                  v-model="formModel.password"
                  type="password"
                  placeholder="请输入新密码"
                  :prefix-icon="Lock"
              />
            </div>
            <div class="input-group">
              <el-input
                  v-model="formModel.repassword"
                  type="password"
                  placeholder="请确认新密码"
                  :prefix-icon="Lock"
              />
            </div>
            <el-button type="primary" class="submit-btn" @click="reSetPassword">
              重置密码
            </el-button>
            <div class="login-link">
              <el-link type="primary" @click="isReSetPassword = false">返回登录</el-link>
            </div>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
// 定义主题色变量
$primary-color: #2C3E50;
$secondary-color: #3498DB;
$accent-color: #E74C3C;
$text-primary: #2C3E50;
$text-secondary: #7F8C8D;
$background-gradient: linear-gradient(135deg, #2C3E50 0%, #3498DB 100%);
$box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);

.login-container {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: $background-gradient;
  position: relative;
  overflow: hidden;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(45deg, rgba(52, 152, 219, 0.1) 0%, rgba(44, 62, 80, 0.1) 100%);
    backdrop-filter: blur(10px);
  }
}

.login-box {
  width: 1000px;
  height: 600px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20px;
  box-shadow: $box-shadow;
  display: flex;
  overflow: hidden;
  position: relative;
  z-index: 1;
}

.info-section {
  flex: 1;
  background: $background-gradient;
  padding: 60px 40px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: white;
  text-align: center;
  position: relative;
  overflow: hidden;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(45deg, rgba(52, 152, 219, 0.2) 0%, rgba(44, 62, 80, 0.2) 100%);
  }

  .logo {
    width: 120px;
    margin-bottom: 40px;
    filter: drop-shadow(0 4px 6px rgba(0, 0, 0, 0.1));
  }

  h1 {
    font-size: 32px;
    font-weight: 600;
    margin-bottom: 20px;
    text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  }

  p {
    font-size: 18px;
    opacity: 0.9;
    line-height: 1.6;
    max-width: 80%;
    margin: 0 auto;
  }
}

.login-section {
  flex: 1;
  padding: 60px 40px;
  display: flex;
  justify-content: center;
  align-items: center;
  background: white;

  .login-content {
    width: 100%;
    max-width: 360px;

    h2 {
      text-align: center;
      margin-bottom: 40px;
      color: $text-primary;
      font-size: 28px;
      font-weight: 600;
    }

    .input-group {
      margin-bottom: 24px;

      :deep(.el-input__wrapper) {
        box-shadow: none;
        border: 2px solid #E5E7EB;
        border-radius: 12px;
        padding: 12px;
        transition: all 0.3s ease;

        &:hover {
          border-color: $secondary-color;
        }

        &:focus-within {
          border-color: $secondary-color;
          box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.1);
        }
      }
    }

    .options {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 24px;
      color: $text-secondary;
    }

    .submit-btn {
      width: 100%;
      height: 48px;
      border-radius: 12px;
      font-size: 16px;
      font-weight: 500;
      background: $secondary-color;
      border: none;
      margin-bottom: 24px;
      transition: all 0.3s ease;

      &:hover {
        background: darken($secondary-color, 5%);
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba(52, 152, 219, 0.2);
      }

      &:active {
        transform: translateY(0);
      }
    }

    .register-link, .login-link {
      text-align: center;
      color: $text-secondary;
      font-size: 14px;

      .el-link {
        font-weight: 500;
        margin-left: 4px;
      }
    }
  }
}

// 响应式设计
@media (max-width: 1024px) {
  .login-box {
    width: 90%;
    max-width: 900px;
  }
}

@media (max-width: 768px) {
  .login-box {
    width: 100%;
    height: 100%;
    flex-direction: column;
    border-radius: 0;
  }

  .info-section {
    padding: 40px 20px;
    flex: 0 0 auto;
    height: 40vh;

    h1 {
      font-size: 24px;
    }

    p {
      font-size: 16px;
    }
  }

  .login-section {
    padding: 40px 20px;
    flex: 1;

    .login-content {
      max-width: 100%;
    }
  }
}

// 添加过渡动画
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>